package com.caption.config;

import org.apache.logging.log4j.ThreadContext;
import org.springframework.core.task.TaskDecorator;

/**
 * TODO 主要是传递父线程交易流水号，注意最后必须要清除流水号
 */
public class ThreadContextTaskDecorator implements TaskDecorator {

    @Override
    public Runnable decorate(Runnable runnable) {
        //传递父线程交易流水号
        String txnId = ThreadContext.peek();
        String txnIdP = ThreadContext.get("txnId");
        return () -> {
            try {
                ThreadContext.push(txnId);
                ThreadContext.put("txnId", txnIdP);
                runnable.run();
            } finally {
                ThreadContext.pop();
                ThreadContext.clearAll();
            }
        };
    }

}